export function rgbToHex(color: string) {
  const reg = /^(rgb|RGB)/
  if (!reg.test(color)) return color
  
  const values = (
    color
      .replace(/rgba?\(/, '')
      .replace(/\)/, '')
      .replace(/[\s+]/g, '')
      .split(',')
  )
  const a = parseFloat((values[3] || '1'));
  const r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255);
  const g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255);
  const b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255);
  
  return (
    "#" 
    + ("0" + r.toString(16)).slice(-2) 
    + ("0" + g.toString(16)).slice(-2) 
    + ("0" + b.toString(16)).slice(-2)
  )
}

export function hexToRgb(color: string) {
  // 16进制颜色值的正则
  const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
  color = color.toLowerCase()
  
  if (reg.test(color)) {
    // 如果只有三位的值，需变成六位，如：#fff => #ffffff
    if (color.length === 4) {
      let colorNew = "#"
      
      for (var i = 1; i < 4; i += 1) {
        colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1))
      }
      
      color = colorNew
    }
    // 处理六位的颜色值，转为RGB
    let colorChange = []
    for (var i = 1; i < 7; i += 2) {
      colorChange.push(parseInt("0x" + color.slice(i, i + 2)))
    }
    
    return "RGB(" + colorChange.join(",") + ")"
    
  } else {
    return color
  }
}

/**
 * @description 十六进制颜色转换为Hsb颜色值
 * @param hex 十六进制的颜色值
 */
export function hexToHsb(hex: string) {
  let r = 0, g = 0, b = 0;

  if (hex.length == 4) {
    r = parseInt(hex[1] + hex[1], 16);
    g = parseInt(hex[2] + hex[2], 16);
    b = parseInt(hex[3] + hex[3], 16);
  } else if (hex.length == 7) {
    r = parseInt(hex.substring(1, 3), 16);
    g = parseInt(hex.substring(3, 5), 16);
    b = parseInt(hex.substring(5, 7), 16);
  }

  r /= 255;
  g /= 255;
  b /= 255;

  let max = Math.max(r, g, b), min = Math.min(r, g, b);
  let h, s, v = max;

  let d = max - min;
  s = max == 0 ? 0 : d / max;

  if (max == min) {
    h = 0; // achromatic
  } else {
    switch (max) {
      case r: h = (g - b) / d + (g < b ? 6 : 0); break;
      case g: h = (b - r) / d + 2; break;
      case b: h = (r - g) / d + 4; break;
    }
    h /= 6;
  }

  return [h * 360, s * 100, v * 100]; // 返回 HSB 值
}

/**
 * @description hex to hsv
 * @param hex 
 * @returns Object
 */
export function hexToHsv(hex: string) {
  // 先将十六进制颜色值转换为RGB值
  let r, g, b;
  if (hex.length === 4) {
    r = parseInt(hex[1] + hex[1], 16);
    g = parseInt(hex[2] + hex[2], 16);
    b = parseInt(hex[3] + hex[3], 16);
  } else if (hex.length === 7) {
    r = parseInt(hex.substring(1, 3), 16);
    g = parseInt(hex.substring(3, 5), 16);
    b = parseInt(hex.substring(5, 7), 16);
  } else {
    throw new Error('Invalid HEX color.');
  }

  // 将RGB值转换为[0, 1]范围内的值
  r /= 255;
  g /= 255;
  b /= 255;

  // 计算最大值、最小值及它们的差
  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);
  const delta = max - min;

  // 初始化HSV值
  let h,
    s,
    v = max;

  // 计算色调H
  if (delta === 0) {
    h = 0; // 灰色，色调未定义
  } else if (max === r) {
    h = 60 * (((g - b) / delta) % 6);
  } else if (max === g) {
    h = 60 * ((b - r) / delta + 2);
  } else {
    h = 60 * ((r - g) / delta + 4);
  }

  // 计算饱和度S
  s = max === 0 ? 0 : delta / max;

  // 将HSV值标准化为[0, 360]范围内的色调和[0, 100]范围内的饱和度和明度
  h = Math.round(h + 360) % 360; // 色调为正值
  s = s; // 饱和度为百分比
  v = v; // 明度为百分比

  return { h, s, v };
}



/**
 * @description 十六进制颜色转rgb返回对象
 * @param hex 
 */
export function hexToRgbObj(hex: string) {
  // 去除前缀#号（如果存在）
  hex = hex.replace(/^#/, '');

  // 如果是三位十六进制数，则将其转换为六位
  if (hex.length === 3) {
      hex = hex.split('').map(function (hexChar) {
          return hexChar + hexChar;
      }).join('');
  }

  // 解析十六进制颜色值
  var r = parseInt(hex.substring(0, 2), 16);
  var g = parseInt(hex.substring(2, 4), 16);
  var b = parseInt(hex.substring(4, 6), 16);

  return {r: r, g: g, b: b};
}

/**
 * @description 检查颜色是否在范围内 适配Android背景颜色黑色大于 rgb(30,30,30), 白色小于 rgb(235,235,235)范围 (非公共方法！慎用！)
 * @param r 
 * @param g 
 * @param b 
 * @returns {Boolean} true:在范围内 false:不在范围内
 */
export function isColorInRange(r: number, g: number, b: number) {
  // 判断颜色是否在黑色范围之外
  const isBlackOutOfRange = r > 30 || g > 30 || b > 30;

  // 判断颜色是否在白色范围之外
  const isWhiteOutOfRange = r < 235 || g < 235 || b < 235;

  // 返回颜色是否在限制范围内
  return isBlackOutOfRange && isWhiteOutOfRange;
}
/*
 * @description Hsb颜色值转换为十六进制颜色值
 * @param h hub色相
 * @param s 饱和度
 * @param v 亮度
 */
export function hsbToHex(h?: number, s?: number, v?: number) {
  let r, g, b, i, f, p, q, t;

  h /= 360;
  s /= 100;
  v /= 100;

  i = Math.floor(h * 6);
  f = h * 6 - i;
  p = v * (1 - s);
  q = v * (1 - f * s);
  t = v * (1 - (1 - f) * s);

  switch (i % 6) {
    case 0: r = v, g = t, b = p; break;
    case 1: r = q, g = v, b = p; break;
    case 2: r = p, g = v, b = t; break;
    case 3: r = p, g = q, b = v; break;
    case 4: r = t, g = p, b = v; break;
    case 5: r = v, g = p, b = q; break;
  }

  return "#" + [r, g, b].map(x => {
    const hex = Math.round(x * 255).toString(16);
    return hex.length === 1 ? '0' + hex : hex;
  }).join('');
}

/**
 * @description 调整亮度，返回Hsb颜色值
 * @param hsb hsb值
 * @param delta 需要调整亮度的值
 */
export function adjustBrightness(hsb: number[], delta: number): number[] {
  return [hsb[0], hsb[1], Math.max(0, Math.min(100, hsb[2] + delta))];
}

export default {
  rgbToHex,
  hexToRgb,
  hexToHsb,
  hexToHsv,
  hexToRgbObj,
  hsbToHex,
  adjustBrightness
}